package transaction.seata.order.service;

import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import transaction.seata.common.entity.Result;
import transaction.seata.common.entity.StatusCode;
import transaction.seata.order.feign.AccountFeign;
import transaction.seata.order.feign.StorageFeign;
import transaction.seata.order.mapper.OrderTblMapper;
import transaction.seata.order.model.OrderTbl;

@Service
@Slf4j
public class OrderService {

    @Autowired
    private AccountFeign accountFeign;
    @Autowired
    private StorageFeign storageFeign;
    @Autowired
    private OrderTblMapper orderMapper;

    @GlobalTransactional(rollbackFor = {Exception.class})
    public Object create(String userId, String commodityCode, Integer count) {
        int orderMoney = count;
        OrderTbl order = new OrderTbl();
        order.setUserId(userId);
        order.setCommodityCode(commodityCode);
        order.setCount(count);
        order.setMoney(orderMoney);
        orderMapper.insert(order);
        Result acc= accountFeign.debit(userId, orderMoney);
        check(acc);
        Result sto= storageFeign.deduct(commodityCode, count);
        check(sto);
        log.info("order 用户 {} 创建订单，数量：{}，金额：{} ->account 账户扣：{}，->storage 库存减少：{}", userId, count, orderMoney, orderMoney, count);
        return "order->account->storage";
    }

    private void check(Result acc) {
        if(!acc.getCode().equals(StatusCode.OK)){
            log.error("调用失败:{}",acc);
            throw new RuntimeException("调用失败"+acc.getMessage());
        }
    }
}
